import { NUMPY_RAND_MAX } from 'common/constants';
import { RootState } from 'store/store';
import { generateSeeds } from 'common/util/generateSeeds';
import { NonNullableGraph } from 'features/nodes/types/types';
import { unset } from 'lodash-es';
import { components } from 'services/api/schema';
import { Batch, BatchConfig } from 'services/api/types';
import {
  CANVAS_COHERENCE_NOISE,
  METADATA_ACCUMULATOR,
  NOISE,
} from './constants';

export const prepareLinearUIBatch = (
  state: RootState,
  graph: NonNullableGraph,
  prepend: boolean
): BatchConfig => {
  const { iterations, shouldRandomizeSeed, seed } = state.generation;

  const data: Batch['data'] = [];

  unset(graph.nodes[METADATA_ACCUMULATOR], 'seed');
  const seeds = generateSeeds({
    count: iterations,
    start: shouldRandomizeSeed ? undefined : seed,
  });

  const zipped: components['schemas']['BatchDatum'][] = [];

  if (graph.nodes[NOISE]) {
    zipped.push({
      node_path: NOISE,
      field_name: 'seed',
      items: seeds,
    });
  }

  if (graph.nodes[METADATA_ACCUMULATOR]) {
    zipped.push({
      node_path: METADATA_ACCUMULATOR,
      field_name: 'seed',
      items: seeds,
    });
  }

  if (graph.nodes[CANVAS_COHERENCE_NOISE]) {
    zipped.push({
      node_path: CANVAS_COHERENCE_NOISE,
      field_name: 'seed',
      items: seeds.map((seed) => (seed + 1) % NUMPY_RAND_MAX),
    });
  }

  data.push(zipped);
  

  const enqueueBatchArg: BatchConfig = {
    prepend,
    batch: {
      graph,
      runs: 1,
      data,
    },
  };

  return enqueueBatchArg;
};
